<template>
	<div id="work-type" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" ref="queryForm" :inline="true">
						<!-- <el-form-item label="选择搜索方式：">
                            <el-select 
                                v-model="searchVal" 
                                filterable 
                                class="m-2" 
                                placeholder="请选择搜索方式" 
                                @change="searchChange"
                                popper-class="set-select"
                                :popper-append-to-body="false"
                            >
                                <el-option
                                    v-for="item in searchOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item> -->
						<!-- 工种名称 -->
						<!-- <template v-if="searchVal === '1'">
                                <el-input v-model="transferVal" placeholder="请输入工种名称" clearable />
                            </template> -->
						<!-- 是否禁用 -->
						<!-- <template v-else-if="searchVal === '2'">
                                <el-select 
                                    v-model="transferVal" 
                                    filterable 
                                    class="m-2" 
                                    placeholder="是否警用" 
                                    @change="acquireChange"
                                    value-key="id"
                                    popper-class="set-select"
                                    :popper-append-to-body="false"
                                >
                                    <el-option
                                        v-for="item in responsiblePle"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </template> -->
						<!-- 工种类型 -->
						<!-- <template v-else>
                                <el-select 
                                    v-model="transferVal" 
                                    filterable 
                                    class="m-2" 
                                    placeholder="工种类型" 
                                    @change="acquireChange"
                                    value-key="id"
                                    popper-class="set-select"
                                    :popper-append-to-body="false"
                                >
                                    <el-option
                                        v-for="item in recordPle"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </template>
                        </el-form-item> -->
						<el-form-item>
							<el-button v-if="$hasPer('WorkType1:add')" @click="nodeClick('')" icon="ele-Plus" type="primary"> 新增 </el-button>
							<el-button v-if="$hasPer('WorkType7:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
							<el-button v-if="$hasPer('WorkType2:download')" icon="ele-Download" @click="downClick">下载模板</el-button>
							<el-upload
							v-if="$hasPer('WorkType3:import')"
								class="upload-demo"
								action="#"
								:auto-upload="false"
								ref="aModel"
								:show-file-list="false"
								:on-change="( file:any ) => { ExcelChange( file , getData ) }"
								:on-success="onSuccess"
								:limit="1"
							>
								<el-button icon="ele-Upload">导入Excel</el-button>
							</el-upload>
							

						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table ref='excelRef' :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" align="center" :index="indexMethod" />
										<el-table-column min-width="100" :show-overflow-tooltip="true" label="工种名称" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="v_WorkName" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.v_WorkName }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="140" :show-overflow-tooltip="true" label="工种类别" align="center">
                                            <el-table-column min-width="140" :show-overflow-tooltip="true" align="center">
                                                <template #header>
                                                    <SearchModel typeId="c_WorkType" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                                </template>
											<template #default="scope">
												{{ scope.row.workTypeName }}
											</template>
                                        </el-table-column>
										</el-table-column>
										<!-- <el-table-column min-width="100" :show-overflow-tooltip="true" label="是否是特殊工种" align="center">
											<template #default="scope">
												<span v-if="scope.row.C_WorkType === 1">是</span>
												<span v-else>否</span>
											</template>
										</el-table-column> -->
										<el-table-column min-width="100" :show-overflow-tooltip="true" label="工种描述" align="center">
											<template #default="scope">
												<span v-if="scope.row.v_WorkTypeDescribe">{{ scope.row.v_WorkTypeDescribe }}</span>
												<span v-else>-</span>
											</template>
										</el-table-column>
										<el-table-column min-width="100" :show-overflow-tooltip="true" label="启用状态" align="center">
											<template #default="scope">
												<span v-if="scope.row.n_isValid === 1">已启用</span>
												<span v-else>未启用</span>
											</template>
										</el-table-column>
										<el-table-column min-width="100" :show-overflow-tooltip="true" label="备注" align="center">
											<template #default="scope">
												<span v-if="scope.row.v_Remake">{{ scope.row.v_Remake }}</span>
												<span v-else>-</span>
											</template>
										</el-table-column>

										<el-table-column prop="createdTime" min-width="160" :show-overflow-tooltip="true" label="创建时间" align="center" />
										<el-table-column prop="createdUserName" min-width="160" :show-overflow-tooltip="true" label="创建者" align="center" />
										<el-table-column prop="updatedTime" min-width="160" :formatter="formatDate" :show-overflow-tooltip="true" label="更新时间" align="center" />
										<el-table-column prop="updatedUserName" min-width="160" :formatter="formatDate" :show-overflow-tooltip="true" label="更新者" align="center" />

										<el-table-column min-width="140" :show-overflow-tooltip="true" label="操作" align="center" fixed="right">
                                            <el-table-column min-width="140" :show-overflow-tooltip="true" align="center" fixed="right">

                                            
                                            <template #header>
                                                
							<el-button @click="searchClick" icon="ele-Search" type="primary" text> 查询 </el-button>
							<el-button @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
                                            </template>
											<template #default="scope">
												<div class="operate-s">
													<el-button v-if="$hasPer('WorkType4:edit')" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary"> 编辑 </el-button>
													<el-button v-if="$hasPer('WorkType5:delete')" @click="deleteHandle(scope.row.n_Id, getData)" class="icon-e" icon="ele-Delete" size="small" text type="danger"> 删除 </el-button>
												</div>
											</template>
										</el-table-column>
                                    </el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<add-edit-work-type :repairInfo="repairInfo" :isUseDialog="isUseDialog" @updateData="getData" @cancelUseClick="cancelUseClick" @controlUseClick="controlUseClick" />
	</div>
</template>
<script lang="ts">
import { defineComponent, ref, Ref, reactive, toRaw, onMounted } from 'vue';
import getTableData from '/@/utils/getTableData';
import { WorkTypeQueryPageList, WorkTypeDelete, UploadBatchImportDataV2 } from '/@/api/centerControl/oms';
import AddEditWorkType from './component/oms/add-edit-work-type.vue';
import { ElMessageBox, ElMessage } from 'element-plus';
// import useCurrentInstance from '/@/utils/hook/useCurrentInstance';
import SearchModel from '/@/views/oms/component/search-model.vue';
import { exportToExcel } from '/@/utils/exportToExcel';
import { getSupplierCountryRegionApi } from '/@/api/centerControl/allInterface';
export default defineComponent({
	name: 'work-type',
	components: {
		AddEditWorkType,
		SearchModel,
	},
	setup(props) {
		// const { proxy } = useCurrentInstance();
		// const $t = proxy.$t;

		const isUseDialog = ref(); // 新增/编辑弹出框隐藏/显示
		const repairInfo = ref(); // 传递子组件数据
		const searchVal = ref('1');
		const transferVal = ref(); // 需要查询的值
		const projectNam = ref(); // 项目名称数
		let searchName = '1';
		let searchObj: any = reactive({});
		const aModel: Ref = ref(null);
		const pathData = ref(import.meta.env.VITE_API_URL + '/'); // 获取地址

		/*** 截取日期格式方法 */
		const formatDate = (row: any, column: any) => {
			// 获取单元格数据
			let data = row[column.property];
			if (data == null) {
				return '-';
			} else {
				return data;
			}
		};

		/*** resetFun */
		const resetFun = () => {
			let newObj = Object.keys(searchObj);
			if (newObj.length !== 0) {
				newObj.map((i: any) => {
					searchObj[i] = '';
				});
			}
		};

		/*** 搜索类型选择事件 searchChange */
		const searchChange = (val: any) => {
			searchName = val;
			transferVal.value = '';
		};

		/*** acquireChange 搜索下拉框选择的数据 ---- 传给接口数据 */
		const acquireChange = (val: any) => {
			// console.log(val)
			searInfo.value = {};
			let newObj = Object.keys(searchObj);
			if (newObj.length !== 0) {
				newObj.map((i: any) => {
					searchObj[i] = '';
					// console.log(i);
				});
			}
			initInfoFun();
		};

		/*** searchClick 查询按钮 */
		const searchClick = () => {
			// resetFun()
			// if(searchName === '1'){ searchObj.v_WorkName = transferVal.value }
			// if(searchName === '2'){ searchObj.n_isValid = transferVal.value }
			// if(searchName === '3'){ searchObj.c_WorkType = transferVal.value }
			let newObj = Object.keys(searInfo.value);
			if (newObj.length !== 0) {
				newObj.map((i: any) => {
					searchObj[i] = searInfo.value[i];
				});
			}
		};

		/*** resetClick 重置按钮 */
		const resetClick = () => {
			searInfo.value = {};
			let newObj = Object.keys(searchObj);
			if (newObj.length !== 0) {
				newObj.map((i: any) => {
					searchObj[i] = '';
					// console.log(i);
				});
			}
			initInfoFun();
		};

		/*** nodeClick 新增/编辑点击事件 */
		const nodeClick = (val: string | object) => {
			val !== '' ? (repairInfo.value = JSON.stringify(toRaw(val))) : (repairInfo.value = '');
			isUseDialog.value = true;
		};

		/*** deleteHandle 删除数据事件 */
		const deleteHandle = async (val: String | Number, updateFun: Function) => {
			ElMessageBox.confirm('请确定是否删除此条数据', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(async () => {
					let param = { n_Id: val };
					try {
						let res: any = await WorkTypeDelete(param);
						if (res.success) {
							updateFun();
						}
					} catch (err) {
						return;
					}
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
				});
		};

		/*** cancelUseClick 取消事件 */
		const cancelUseClick = () => {
			isUseDialog.value = false;
		};

		/*** controlUseClick 提交事件 */
		const controlUseClick = () => {
			isUseDialog.value = false;
		};

		/*** downClick 下载模板 */
		const downClick = () => {
			// window.location.href = 'www.baidu.com' // 覆盖当前页
			window.open(toRaw(pathData.value) + 'Upload/SMS/Batch/WorkType.xlsx', '_blank'); // 打开新页面
		};

		/*** ExcelChange 导入Excel */
		const ExcelChange = (item: any, updateFun: Function) => {
			let arr: any = [];
			let reader = new FileReader();
			reader.readAsDataURL(item.raw);
			reader.onload = (e: any) => {
				let base64String = e.target.result;
				let param: any = new Object();
				param.ModelType = 'WorkType';
				param.FileContent = base64String;
				arr.push(item.raw);
				uploadFun(arr, updateFun);
			};
		};
		/*** uploadFun 批量导入数据接口 */
		const uploadFun = async (arr: any, updateFun: Function) => {
			aModel.value.clearFiles();
			let res: any = await UploadBatchImportDataV2({ file: arr });
			if (res.success) {
				ElMessage.success('导入成功');
				updateFun();
			}
		};

		/*** onSuccess 文件上传成功时的钩子函数 */
		const onSuccess = (item: any) => {
			console.log(item, 'item');
		};

		/*** 初始化数据 */
		const basicsInfo: any = ref([]);
		const initInfoFun = () => {
			basicsInfo.value = [
				{
					typeId: 'c_WorkType', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
					typeNam: '', // 输入类型(number,text等) --- 选填
					searchVal: 'c_WorkType', // 查询字段 --- 必填
					defaultVal: '', // 字段默认值 --- 选填
					placeholder: '工种类型', // placeholder数据
					defaultProp: recordPle, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
					eventType: '', // 事件类型（如burl/change等） --- 选填
					defaultEvent: '', // 事件名称 --- 选填
				},
				{
					typeId: 'v_WorkName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
					typeNam: '', // 输入类型(number,text等) --- 选填
					searchVal: 'v_WorkName', // 查询字段 --- 必填
					defaultVal: '', // 字段默认值 --- 选填
					placeholder: '工种名称', // placeholder数据
					defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
					eventType: '', // 事件类型（如burl/change等） --- 选填
					defaultEvent: '', // 事件名称 --- 选填
				},
			];
		};

		const searInfo: any = ref();
		const searchHandel = (val: any) => {
			searInfo.value = val;
		};

		const recordPle =ref([]);

		onMounted(async () => {
			const res = await getSupplierCountryRegionApi({ TypeCode: 'omsJobtype' });
			recordPle.value = res.data.map((i: any) => {
		return {
			label: i.value,
			value: i.id,
		};
	});
			await initInfoFun();

		});

		  /*** ================================= 导出数据函数操作 ================================= */
		  const excelRef: any = ref(null);
        const handleExport = () => {
            if(excelRef.value){
                if(excelRef.value.data.length !== 0){
                    let tableExcel: any = [];
                    let tableArr = excelRef.value.data;
                    tableArr.map((item: any) => {
                        let tableObj: any = {};
                        tableObj['工种名称'] = item.v_WorkName ? item.v_WorkName : '-';
                        tableObj['工种类别'] = item.workTypeName  ? item.workTypeName : '-';
						tableObj['工种描述'] = item.v_WorkTypeDescribe ? item.v_WorkTypeDescribe : '-';
                        tableObj['启用状态'] = item.n_isValid ? item.n_isValid : '-';
                        tableObj['备注'] = item.v_Remake ? item.v_Remake : '-';

                        tableObj['创建人'] = item.createdUserName ? item.createdUserName : '-';
                        tableObj['创建时间'] = item.createdTime ? item.createdTime : '-';
                        tableObj['更新人'] = item.updatedUserName ? item.updatedUserName : '-';
                        tableObj['更新时间'] = item.updatedTime ? item.updatedTime : '-';
                        tableExcel.push(tableObj);
                    });
                    exportToExcel(tableExcel,'工种类型.xlsx');
                }else{
                    ElMessage({
                        type: 'error',
                        message: '暂无数据导出',
                    })
                }
            }
        }

		return {
			...getTableData(WorkTypeQueryPageList, {}, searchObj),
			isUseDialog,
			cancelUseClick,
			controlUseClick,
			nodeClick,
			repairInfo,
			deleteHandle,
			resetClick,
			searchClick,
			downClick, // 下载模板
			ExcelChange, // 导入Excel
			onSuccess,
			aModel,

			searchOptions: [
				{
					value: '1',
					label: '工种名称',
				},
				{
					value: '2',
					label: '是否禁用',
				},
				{
					value: '3',
					label: '工种类型',
				},
			], // 搜索方式
			searchVal,
			searchChange,
			transferVal,
			acquireChange,
			projectNam, // 工种名称数据
			responsiblePle: [
				{ label: '是', value: 2 },
				{ label: '否', value: 1 },
			], // 工种编号数据
			recordPle, // 工种类型数据
			formatDate,
			pathData,
			searInfo,
			searchHandel,
            basicsInfo,
			handleExport,excelRef
		};
	},
});
</script>
<style lang="scss">
@import './style/public.scss';
</style>
<style scoped lang="scss">
#work-type {
	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}
	:deep(.el-card__body) {
		height: 100%;
	}
	:deep(.el-card) {
		border: none !important;
	}
	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}
	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}
	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}
}
</style>
